<?php
/**
 * Copyright (c) 2008 Pascal MARTIN <contact@pascal-martin.fr>,
 *                    Rémi PERROUD <remi.perroud@gmail.com>
 *      http://code.google.com/p/simpleguestbook/
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @author Pascal MARTIN
 * @version $Id: AdminController.php 23 2008-09-26 18:22:00Z pascal.martin.pmn $
 *
 */

require_once(dirname(__FILE__) . '/BaseController.php');

class AdminController extends BaseController
{
    
    public function newAction()
    {
        $request = $this->getRequest();
        $form = $this->_getCommentForm();
        if ($request->isPost()) {
            if ($form->isValid($request->getPost())) {
                $daoComments = new Comments();
                $user = new Zend_Session_Namespace('user');
                
                $texte = Service_HTMLPurifier::convert($this->_getParam('texte'));
                
                $data = array(
                    'id_user' => $user->id,
                    'date' => Zend_Date::now()->get(Zend_Date::ISO_8601),
                    'texte' => $texte,
                    'is_visible' => 1
                );
                try {
                    $daoComments->insert($data);
                } catch (Exception $e) {
                    echo '<p>' . htmlentities($e->getMessage()) . '</p>';
                    echo "<p><em>Astuce : avez-vous bien rendu le fichier de base de données accessible en écriture par Apache / PHP ?<em></p>";
                    die;
                }
                $this->_helper->redirector->gotoRoute(array(), 'index');
            }
        }
        $this->view->form = $form;
    } // newAction
    
    
    public function loginAction()
    {
        $request = $this->getRequest();
        $form = $this->_getLoginForm();
        $this->view->messages = array();
        if ($request->isPost()) {
            if ($form->isValid($request->getPost())) {
                $auth = Zend_Auth::getInstance();
                $auth->setStorage(new Zend_Auth_Storage_Session('user'));
                $authAdapter = new Zend_Auth_Adapter_DbTable(
                    Zend_Registry::get('db'),
                    'users',
                    'login',
                    'password'
                );
                $authAdapter->setIdentity($this->_getParam('login'))
                    ->setCredential(sha1($this->_getParam('password')));
                $result = $auth->authenticate($authAdapter);
                if (!$result->isValid()) {
                    $this->view->messages = $result->getMessages();
                } else {
                    
                    $daoUsers = new Users();
                    $user = $daoUsers->findByLogin(Zend_Auth::getInstance()->getIdentity());
                    $userNamespace = new Zend_Session_Namespace('user');
                    $userNamespace->id = $user->id;
                    $userNamespace->login = $user->login;
                    $userNamespace->email = $user->email;
                    $this->_helper->redirector->gotoRoute(array(), 'adminNew');
                }
            }
        }
        $this->view->form = $form;
        $this->_helper->layout->disableLayout();
    } // loginAction
    
    
    public function logoutAction()
    {
        Zend_Auth::getInstance()->clearIdentity();
        Zend_Session::destroy();
        $this->_helper->redirector->gotoRoute(array(), 'index');
    } // logoutAction
    
    
    
    public function preDispatch()
    {
        if (!(
                $this->getRequest()->getControllerName() === 'admin'
                && $this->getRequest()->getActionName() === 'login'
            )) {
            if (!Zend_Session::sessionExists()) {
                $this->_helper->redirector->gotoRoute(array(), 'adminLogin');
            } else {
                if (Zend_Auth::getInstance()->hasIdentity() === false) {
                    $this->_helper->redirector->gotoRoute(array(), 'adminLogin');
                }
            }
        }
    } // preDispatch
    
    
    protected function _getCommentForm()
    {
        $form = new Zend_Form();
        
        $texte = $form->addElement('textarea', 'texte', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                array('StringLength', false, array(5)),
            ),
            'required'   => true,
            'label'      => 'Contenu du commentaire',
        ));
        
        $form->addElement('hash', 'csrf', array(
            'salt' => 'glop'
        ));
        
        $ok = $form->addElement('submit', 'ok', array(
            'required' => false,
            'ignore'   => true,
            'label'    => 'Enregistrer',
        ));
        
        $form->setAction('/admin/new');
        $form->setMethod('post');
        return $form;
    } // _getCommentForm
    
    
    protected function _getLoginForm()
    {
        $form = new Zend_Form();
        
        $login = $form->addElement('text', 'login', array(
            'filters'    => array('StringTrim', 'StringToLower'),
            'validators' => array(
                'Alnum',
                array('StringLength', false, array(3, 20)),
            ),
            'required'   => true,
            'label'      => 'Login',
        ));
		
        $password = $form->addElement('password', 'password', array(
            'filters'    => array('StringTrim'),
            'validators' => array(
                'Alnum',
                array('StringLength', false, array(6, 20)),
            ),
            'required'   => true,
            'label'      => 'Password',
        ));
		
        /*$form->addElement('hash', 'csrf', array(
            'salt' => 'hello'
        ));*/
        
        $ok = $form->addElement('submit', 'ok', array(
            'required' => false,
            'ignore'   => true,
            'label'    => 'Login',
        ));
        
        $form->setAction('/admin/login');
        $form->setMethod('post');
        
        return $form;
    } // _getLoginForm
    
    
} // class AdminController
